
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import socketserver
import json,os



PATH = PATH = os.path.dirname(__file__)
APPAGENT = "agent" + os.sep + "resp.txt"

class MyTCPHandler(socketserver.BaseRequestHandler):
    aPath = PATH + os.sep + APPAGENT

    def handle(self):
        while True:
            self.data = self.request.recv(1024).strip()
            try:
                jd = self.data.decode('utf-8')
                print(jd)
                self.match_route(jd)
            except Exception as e:
                print("不可识别数据:")
                print(self.data)
            if not self.data:
                self.finish()
                break
    def match_route(self,params):
        jsonp = json.loads(params)
        if "id" in jsonp.keys():
            if jsonp['id'] == 4:
                self.write_txt(self.aPath,params)
                print("响应信息写入成功!")
        elif "type" in jsonp.keys():
            if jsonp['type'] == "safetool":
                result = self.read_txt(self.aPath)
                print(json.loads(result)['reflection_response']['result']["object"]['reference'])
    def write_txt(self,filePath,content):
        with open(filePath,"w",encoding="utf-8",errors="ignore") as file_to_write:
            file_to_write.write(content)

    def read_txt(self,filePath):
        with open(filePath,"r") as file_to_read:
            result = file_to_read.readline()
        return json.loads(result)

    def finsh(self):
        print("socket服务退出!")


if __name__ == "__main__":
    host = "192.168.22.103"
    port = 9191
    server = socketserver.ThreadingTCPServer((host, port), MyTCPHandler)
    print('Socket服务开启！')
    print('监听端口:9191') 
    server.serve_forever()
